package com.wfuhui.book.ui.cart;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.wfuhui.book.R;
import com.wfuhui.book.model.Cart;
import com.wfuhui.book.ui.book.DetailActivity;
import com.wfuhui.book.ui.order.ConfirmActivity;
import com.wfuhui.book.util.Constant;
import com.wfuhui.book.util.GlideImageLoader;
import com.wfuhui.book.util.PreferencesService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class CartFragment extends Fragment {

    private RecyclerView recyclerView;

    private List<Cart> cartList = new ArrayList<>();

    private CartQAdapter cartAdapter1 = new CartQAdapter(R.layout.shelf_item);

    private TextView totalTxt;

    private Button payBtn;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_cart, container, false);
        totalTxt = root.findViewById(R.id.total);

        payBtn = root.findViewById(R.id.pay);
        recyclerView = root.findViewById(R.id.cart);
        cartAdapter1.addChildClickViewIds(R.id.remove,R.id.cb,R.id.name);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(cartAdapter1);
        cartAdapter1.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if(view.getId()==R.id.remove){
                    removeCartItem(position);
                }
                if(view.getId()==R.id.name){
                    Intent intent = new Intent(getActivity(), DetailActivity.class);
                    intent.putExtra("id", cartList.get(position).getBookId());
                    getActivity().startActivity(intent);
                }
                if(view.getId()==R.id.cb){
                    if(cartList.get(position).isselect)
                        cartList.get(position).isselect = false;
                    else
                        cartList.get(position).isselect = true;
                    updatesum();
                }
            }
        });

        payBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean hasselected = false;
                for (Cart c : cartList) {
                    if(c.isselect){
                        hasselected = true;
                        break;
                    }
                }
                if(!hasselected)
                {
                    Toast.makeText(getActivity(),"请选择产品下单！",Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(getActivity(), ConfirmActivity.class);
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < cartList.size(); i++) {
                    if (!cartList.get(i).isselect) {
                        continue;
                    }
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("cartid", cartList.get(i).getId());
                        jsonObject.put("bookId", cartList.get(i).getBookId());
                        jsonObject.put("author", cartList.get(i).getAuthor());
                        jsonObject.put("bookName", cartList.get(i).getBookName());
                        jsonObject.put("price", cartList.get(i).getPrice());
                        jsonObject.put("picUrl", cartList.get(i).getPicUrl());
                        jsonObject.put("num", cartList.get(i).getNum());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    jsonArray.put(jsonObject);
                }
                intent.putExtra("payBook", jsonArray.toString());
                startActivity(intent);
            }
        });

        getCarts();
        return root;
    }

    @SuppressLint("SuspiciousIndentation")
    private void updatesum() {
        Double sum = 0d;
        for (Cart c : cartList) {
            if(c.isselect)
                sum += c.getPrice();
        }
        totalTxt.setText("￥ "+sum);
    }

    void removeCartItem(int position) {

        PreferencesService preferencesService = new PreferencesService(this.getActivity());
        String token = preferencesService.get("token");
        if(token == null || "".equals(token)){
            return;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/cart/del?id="+cartList.get(position).getId())
                .addHeader("token", token)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/cart/del", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });

        getCarts();
    }

    @Override
    public void onResume() {
        super.onResume();
        getCarts();
    }

    private void getCarts(){
        PreferencesService preferencesService = new PreferencesService(this.getActivity());
        String token = preferencesService.get("token");
        if(token == null || "".equals(token)){
            return;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "/api/cart/list")
                .addHeader("token", token)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("/api/cart/list", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("/api/cart/list", "onResponse: " + result);
                try {
                    JSONObject json = new JSONObject(result);
                    int code = json.getInt(Constant.RESP_CODE);
                    if(code == 0){
                        cartList = new ArrayList<>();
                        JSONArray bookArr = json.getJSONArray("shelfList");
                        List<String> picUrls = new ArrayList<String>();
                        for(int i = 0; i < bookArr.length(); i++){
                            JSONObject bookJson = bookArr.getJSONObject(i);
                            Cart cart = new Cart();
                            cart.setBookId(bookJson.getInt("bookId"));
                            cart.setAuthor(bookJson.getString("author"));
                            cart.setId(bookJson.getInt("id"));
                            cart.setBookName(bookJson.getString("bookName"));
                            cart.setPicUrl(bookJson.getString("picUrl"));
                            if(!bookJson.isNull("price"))
                                cart.setPrice (bookJson.getDouble("price"));
                            cart.setNum(bookJson.getInt("num"));
                            cartList.add(cart);
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                cartAdapter1.setNewData(cartList);
                                updatesum();
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


}
